package uk.ac.glasgow.demosocs.impl.ui;

import uk.ac.glasgow.clui.CommandDescription;

import uk.ac.glasgow.clui.ArgumentsDescription;
import uk.ac.glasgow.clui.MinimumArguments;
import uk.ac.glasgow.clui.SystemCommand;
import uk.ac.glasgow.clui.SystemCommandException;
import uk.ac.glasgow.demosocs.Election;
import uk.ac.glasgow.demosocs.VotingSystem;
import uk.ac.glasgow.demosocs.impl.ElectionImpl;
import uk.ac.glasgow.demosocs.impl.OneOfNVoteStub;
import uk.ac.glasgow.demosocs.impl.RankedVote;
import uk.ac.glasgow.demosocs.impl.RefVote;

@MinimumArguments(1)
@CommandDescription("Cast a vote in the currently selected election for the specified candidate.")
@ArgumentsDescription("<candidate>")
public class CastVoteCommand extends SystemCommand<VotingSystem> {

	public CastVoteCommand(VotingSystem facade) {
		super(facade);
	}

	@Override
	public String processCommand(String[] arguments)
			throws SystemCommandException {

		Election election = facade.getCurrentElection();

		if (election == null)
			throw new SystemCommandException("No current election set.");

		String guid = facade.getCurrentUserGUID();
		if (guid == null)
			throw new SystemCommandException("No current user set.");

		if (((ElectionImpl)election).getType().equalsIgnoreCase("AV")) {
			facade.castVote(new RankedVote(arguments));
			
			String return_s = "A vote was cast for [";
			for (String s: arguments)
			{
				return_s += s + " ";
			}
			return return_s + "].";
		} else if(((ElectionImpl)election).getType().equalsIgnoreCase("R")) {
			if(arguments[0].equalsIgnoreCase("yes")) {
				facade.castVote(new RefVote(1));
				return "A vote was cast for YES.";
			} else if(arguments[0].equalsIgnoreCase("no")) {
				facade.castVote(new RefVote(0));
				return "A vote was cast for NO.";
			} else {
				return "This is a referendum. Only yes/no votes can be cast.";
			}
		} else {
			String candidate = arguments[0];

			facade.castVote(new OneOfNVoteStub(candidate));
			
			return "A vote was cast for [" + candidate + "].";
		}
	}
}
